package com.ophelisis.actions.userMgmt;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.ophelisis.common.util.CryptUtils;
import com.ophelisis.persistence.dao.PortalUserDAO;
import com.ophelisis.persistence.domain.PortalUserVO;

/** <pre>
 * Class : com.ophelisis.actions.userMgmt.PortalUserMgmt / PortalUserMgmt.java
 * 	Define Class Object : 
 * <br>
 * </pre>
 * @author hlee / apexcns,Inc.
 * @version 1.0
 * @see javadoc
 * @since 2013. 07. 29.
 */
@Controller
public class PortalUserMgmt {
	@Autowired
	PortalUserDAO userDAO;
	
	private List<PortalUserVO> userList;
	private String sResult = "";
	
	private Log log = LogFactory.getLog(this.getClass());
	private static final String _LogPrefixStr = "UserMgmt Log> ";

	@RequestMapping(value="portalUserMgmt.action")
	public ModelAndView portalUserMgmt(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="target", defaultValue="umMain") String sTarget,
			@RequestParam(value="_groupId", defaultValue="0") String sMenuGroupId,
			@RequestParam(value="_menuId", defaultValue="0") String sMenuId,
			@RequestParam(value="_menuNm", defaultValue="") String sMenuNm,
			@RequestParam(value="_menuAuth", defaultValue="0") String sUserMenuAuth,
			@RequestParam(value="_prevUpCode", defaultValue="") String sPrevUpCode,
			@RequestParam(value="_prevCode", defaultValue="") String sPrevCode,
			@RequestParam(value="_startRowNo", defaultValue="0") String sStartRowNo,
			@RequestParam(value="_pageSize", defaultValue="15") String sPageSize,
			@RequestParam(value="searchVal1", defaultValue="") String sSearchVal1,
			@RequestParam(value="isNew", defaultValue="Y") String isNew,
			@ModelAttribute PortalUserVO portalUserVO) throws Exception {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession(false);

		log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
		log.debug(_LogPrefixStr + "|" + " PortalUserMgmt called !!!");
		log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
		
		try {
			// 공통 요소
			mav.addObject("_groupId", sMenuGroupId);
			mav.addObject("_menuId", sMenuId);
			mav.addObject("_menuNm", sMenuNm);
			mav.addObject("_menuAuth", sUserMenuAuth);
			mav.addObject("_prevUpCode", sPrevUpCode);
			mav.addObject("_prevCode", sPrevCode);
			mav.addObject("_startRowNo", sStartRowNo);
			mav.addObject("_pageSize", sPageSize);
			mav.addObject("searchVal1", sSearchVal1);

			int iStartRowNo = Integer.parseInt(sStartRowNo); // 해당 페이지의 시작 번호
			int iPageSize = Integer.parseInt(sPageSize); // 한 페이지에 보일 레코드 수
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("startRowNo", iStartRowNo); // 공통 코드 그룹 ID (1:메뉴 유형)
			params.put("pageSize", iPageSize);
			params.put("searchVal1", sSearchVal1);
			params.put("userId", sPrevCode);
			params.put("updateUser", (String)session.getAttribute("userId"));
			
			if (sTarget.equals("umMain")) {
				mav = returnMgmt("main", mav, params);
			} else if (sTarget.equals("umList")) {
				mav = returnMgmt("list", mav, params);
			} else if (sTarget.equals("umDetail")) {
				mav = returnMgmt("detail", mav, params);
			} else if (sTarget.equals("umAdd")) {
				mav.setViewName("/WEB-INF/jsp/userMgmt/portalUserMgmtAdd.jsp");
				
				log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
				log.debug(_LogPrefixStr + "|" + " PortalUserMgmt Add-Page called !!!");
				log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
			} else if (sTarget.equals("umDelete")) {
				try {
					sResult = userDAO.setPortalUserDelete(params) > 0 ? "정상적으로 처리되었습니다." : "처리에 실패하였습니다.<BR/>관리자에게 문의하여 주십시오."; // 유저 정보 업데이트
				} catch (Exception e) {
					log.error("DB 정보 획득 failed!", e);
				}
				
				mav.addObject("result", sResult);
				
				mav = returnMgmt("list", mav, params);
			} else if (sTarget.equals("umSave")) {
				String EncUserPw = CryptUtils.encrypt(portalUserVO.getUserPassword());
				
				portalUserVO.setUpdateUser((String)session.getAttribute("userId"));
				portalUserVO.setUserPassword(EncUserPw);
				
				try {
					sResult = (isNew.equals("Y") ? userDAO.setPortalUserAdd(portalUserVO) : userDAO.setPortalUserModify(portalUserVO)) > 0 ? "정상적으로 처리되었습니다." : "처리에 실패하였습니다.<BR/>관리자에게 문의하여 주십시오."; // 유저 정보 업데이트

					params.put("userId", portalUserVO.getUserId());
				} catch (Exception e) {
					log.error("DB 정보 획득 failed!", e);
				}
				request.setAttribute("result", sResult);
				
				mav = returnMgmt("detail", mav, params);
			} else if (sTarget.equals("umRestore")) {
				portalUserVO.setUpdateUser((String)session.getAttribute("userId"));

				try {
					sResult = userDAO.setPortalUserModify(portalUserVO) > 0 ? "정상적으로 처리되었습니다." : "처리에 실패하였습니다.<BR/>관리자에게 문의하여 주십시오."; // 유저 정보 업데이트

					params.put("userId", portalUserVO.getUserId());
				} catch (Exception e) {
					log.error("DB 정보 획득 failed!", e);
				}
				request.setAttribute("result", sResult);
				
				mav = returnMgmt("list", mav, params);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}

		return mav;
	}
	
	public ModelAndView returnMgmt(
			@RequestParam(value="cmd", defaultValue="list") String cmd,
			@ModelAttribute ModelAndView mav,
			Map<String, Object> params) throws Exception {
		if (cmd.equals("main")) {
			mav.setViewName("/WEB-INF/jsp/userMgmt/portalUserMgmt.jsp");

			log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
			log.debug(_LogPrefixStr + "|" + " PortalUserMgmt Main-Page called !!!");
			log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
		} else if (cmd.equals("list")) {
			int iTotalCount = 0;
			
			try {
				iTotalCount = userDAO.getPortalUserListCnt(params); // 쿼리 결과 카운트
				userList = userDAO.getPortalUserList(params); // 쿼리 결과
			} catch (Exception e) {
				log.error("DB 정보 획득 failed!", e);
			}

			mav.addObject("totalCnt", String.valueOf(iTotalCount));
			mav.addObject("userList", userList);
			mav.setViewName("/WEB-INF/jsp/userMgmt/portalUserMgmtList.jsp");
			
			log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
			log.debug(_LogPrefixStr + "|" + " PortalUserMgmt List-Page called !!!");
			log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
		} else if (cmd.equals("detail")) {
			try {
				userList = userDAO.getPortalUserDetail(params); // 쿼리 결과
			} catch (Exception e) {
				log.error("DB 정보 획득 failed!", e);
			}

			mav.addObject("userList", userList);
			mav.setViewName("/WEB-INF/jsp/userMgmt/portalUserMgmtDetail.jsp");
			
			log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
			log.debug(_LogPrefixStr + "|" + " PortalUserMgmt Detail-Page called !!!");
			log.debug(_LogPrefixStr + "|" + "------------------------------------------------------------------------------------");
		}
		
		return mav;
	}
}

